package com.example.demo.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * *  Author:zlf
 * *  2020/10/26 16:44
 **/
public class Utility {
    public static String MD5(String str) {
        if (str != null && !str.equals("")) {
            try {
                byte[] btInput = str.getBytes();
                MessageDigest mdInst = MessageDigest.getInstance("MD5");
                mdInst.update(btInput);
                byte[] md = mdInst.digest();
                return new String(byteArrayToStr(md));
            } catch (NoSuchAlgorithmException var4) {
                System.out.println("Not support MD5");
                return null;
            }
        } else {
            return null;
        }
    }

    public static String byteArrayToStr(byte[] buf) {
        return byteArrayToStr(buf, buf.length);
    }

    public static String byteArrayToStr(byte[] buf, int length) {
        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < length; ++i) {
            sb.append(byteToString(buf[i]));
        }

        return sb.toString();
    }

    public static String byteToString(int b) {
        return Integer.toHexString(b & 255 | '\uff00').substring(2);
    }

    public static String byteArrayToString(byte[] buf) {
        StringBuffer sb = new StringBuffer();
        byte[] var2 = buf;
        int var3 = buf.length;

        for (int var4 = 0; var4 < var3; ++var4) {
            byte b = var2[var4];
            sb.append(Integer.toHexString(b & 255) + " ");
        }

        return sb.toString();
    }
}
